//
//  XDToWithdrawViewController.m
//  xindailianmeng
//
//  Created by 张东 on 2017/3/7.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//


/**      提现 绑卡           */

#import "XDToWithdrawViewController.h"
#import "AFHTTPSessionManager+POST.h"
#import "SDWebImageManager.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"
#import "XDCheckWithdrawViewController.h"
#import "ZHRTBasicMethod.h"
#import "XDGetCityViewController.h"
#import "XDGetSubBankNameController.h"
@interface XDToWithdrawViewController ()<UITextFieldDelegate>

@property (nonatomic, weak) UITextField *bankNum;

@property (nonatomic, weak) UIButton *bankNameBtn;

@property (nonatomic, weak) UILabel *cityLb;

@property (nonatomic, weak) UILabel *subBranch;

@property (nonatomic, weak) UIButton *subBranchBtn;

@property (nonatomic, weak) UIButton *nextBtn;

@property (nonatomic, copy) NSString *bankCode;

@property (nonatomic, copy) NSString *accountProvince;

@property (nonatomic, copy) NSString *cityCode;

@property (nonatomic, weak) UIScrollView *scrollView;
@end

@implementation XDToWithdrawViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
    [df removeObjectForKey:@"toWithdraw"];
    [df synchronize];
    self.title = @"提现";
    self.view.backgroundColor = kColorRGB(234, 234, 234);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"提现须知"  style:UIBarButtonItemStylePlain target:self action:@selector(rightItem)];
    rightItem.tintColor = kColorRGB(187,147,115);
    self.navigationItem.rightBarButtonItem = rightItem;
    [self setupUI];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hotCityNoti:) name:@"hotCityArr" object:nil];
//    subCityName
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subCityNoti:) name:@"subCityName" object:nil];
    
    if (self.bankNum.text.length > 14 && self.bankCode && self.cityLb.text.length > 0 && self.subBranch.text.length > 0) {
        self.nextBtn.enabled = YES;
    } else {
        self.nextBtn.enabled = NO;
    }
}
- (void)setupUI {
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:kScreenB];
    scrollView.backgroundColor = kColorRGB(234, 234, 234);
    scrollView.contentSize =CGSizeMake(0, kScreenH + 20);
    self.scrollView = scrollView;
    scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:scrollView];
    
    UITextField *bankNum = [self createTextFieldWithFrame:CGRectMake(0, 10, kScreenW, 50) textFont:kBaseFont_(16) textColor:kColorRGB(51, 51, 51) placeholder:@"请输入提现银行卡号" placeholderFont:kBaseFont_(13) leftTitle:@"银行卡号" delegate:self inView:scrollView tag:100];
    bankNum.backgroundColor = [UIColor redColor];
    self.bankNum = bankNum;
    
    UITextField *bankName = [self createTextFieldWithFrame:CGRectMake(0, CGRectGetMaxY(bankNum.frame) + 10, kScreenW, 50) textFont:kBaseFont_(16) textColor:kColorRGB(51, 51, 51) placeholder:@"" placeholderFont:kBaseFont_(13) leftTitle:@"所属银行" delegate:self inView:scrollView tag:101];
    bankName.userInteractionEnabled = NO;
    UIButton *bankNameBtn = [self createBtnWithTitle:@"目前暂不支持招商、邮政、交通银行卡"];
    [bankName addSubview:bankNameBtn];
    self.bankNameBtn = bankNameBtn;
    
//    请选择银行卡所在城市
    UILabel *cityLb = [self createLableWithBtnFrame:CGRectMake(0, CGRectGetMaxY(bankName.frame) + 10, kScreenW, 50) btnTitle:@"银行卡所在城市" lableText:@"" tag:102];
    self.cityLb = cityLb;
//    请选择银行卡所在支行
    UILabel *subBranch = [self createLableWithBtnFrame:CGRectMake(0, CGRectGetMaxY(bankName.frame) + 70, kScreenW, 50) btnTitle:@"银行卡支行" lableText:@"" tag:103];
    self.subBranch = subBranch;
    self.subBranchBtn = [scrollView viewWithTag:103];
//    self.subBranchBtn.userInteractionEnabled = NO;
    
    
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenW - 240) / 2, CGRectGetMaxY(bankName.frame) + 158, 240, 40)];
    [nextBtn setImage:[UIImage imageNamed:@"next_fill_nor"] forState:UIControlStateDisabled];
    nextBtn.enabled = NO;
    [nextBtn setImage:[UIImage imageNamed:@"next_fill_hieght"] forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.nextBtn = nextBtn;
    [scrollView addSubview:nextBtn];
    
}

- (UIButton *)createBtnWithTitle:(NSString *)title  {
    UIButton *depositBankBtn =
    [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenW - 15, 50)];
    
    [depositBankBtn setTitle:title forState:UIControlStateNormal];
    [depositBankBtn setTitleColor:kColorRGB(153,153,153) forState:UIControlStateNormal];
    depositBankBtn.titleLabel.font = kBaseFont_(13);
    depositBankBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    depositBankBtn.userInteractionEnabled = NO;
    return depositBankBtn;
}


- (UILabel *)createLableWithBtnFrame:(CGRect)frame btnTitle:(NSString *)btnTitle lableText:(NSString *)lableText  tag:(NSInteger)tag{
    
    UIButton *backgroundBtn = [[UIButton alloc] initWithFrame:frame];
    [backgroundBtn setBackgroundImage:[UIImage imageNamed:@"textfield-1"] forState:UIControlStateNormal];
    [backgroundBtn setBackgroundImage:[UIImage imageNamed:@"textfield-1"] forState:UIControlStateHighlighted];
    [backgroundBtn setTitle:btnTitle forState:UIControlStateNormal];
    [backgroundBtn setImage:[UIImage imageNamed:@"nextInd"] forState:UIControlStateNormal];
    [backgroundBtn setImage:[UIImage imageNamed:@"nextInd"] forState:UIControlStateHighlighted];
    [backgroundBtn setTitleColor:kColorRGB(102,102,102) forState:UIControlStateNormal];
    backgroundBtn.titleLabel.font = kBaseFont_(14);
    backgroundBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
    backgroundBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    backgroundBtn.imageEdgeInsets = UIEdgeInsetsMake(0, kScreenW - 30 - 6, 0, 0);
    backgroundBtn.titleEdgeInsets = UIEdgeInsetsMake(0,-6, 0, 0);
    [backgroundBtn addTarget:self action:@selector(backgroundBtn:) forControlEvents:UIControlEventTouchUpInside];
    backgroundBtn.tag = tag;
    [self.scrollView addSubview:backgroundBtn];
    
    UILabel *cityLb = [[UILabel alloc] initWithFrame:CGRectMake(150, 0, kScreenW - 180, 50)];
    cityLb.text = lableText;
    cityLb.font = kBaseFont_(16);
    cityLb.textColor = kColorRGB(51, 51, 51);
    cityLb.textAlignment = NSTextAlignmentRight;
    [backgroundBtn addSubview:cityLb];
    return cityLb;
}

//修改UITextField的placeholder字体并垂直居中
- (NSAttributedString *)textFieldAttributedPlaceholderWith:(UITextField *)textField placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont  {
    NSMutableParagraphStyle *style = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    style.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - placeholderFont.lineHeight) / 2.0;
    NSAttributedString *attr = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName:placeholderFont, NSParagraphStyleAttributeName : style}];
    return attr;
}

- (UITextField *)createTextFieldWithFrame:(CGRect)frame textFont:(UIFont *)textFont textColor:(UIColor *)textColor placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont leftTitle:(NSString *)leftTitle delegate:(id)obj inView:(UIView *)inView tag:(NSInteger)tag {
    
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
    
    textField.background = [UIImage imageNamed:@"textfield-1"];
    textField.textAlignment = NSTextAlignmentRight;
    textField.textColor =  textColor;
    textField.font = textFont;
    textField.tag = tag;
    
    textField.attributedPlaceholder = [self textFieldAttributedPlaceholderWith:textField placeholder:placeholder placeholderFont:placeholderFont];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 80, 48)];
    leftView.backgroundColor = [UIColor whiteColor];
    
    UILabel *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 80, 48)];
    nameLb.text = leftTitle;
    nameLb.textColor = kColorRGB(102,102,102);
    nameLb.font = kBaseFont_(14);
    nameLb.textAlignment = NSTextAlignmentLeft;
    [leftView addSubview:nameLb];
    textField.leftView = leftView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    
    textField.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 15, 48)];
    textField.rightViewMode = UITextFieldViewModeAlways;
    
    textField.delegate = obj;
    [inView addSubview:textField];
    return textField;
}

- (void)backgroundBtn: (UIButton *)btn {
    [self.bankNum resignFirstResponder];
    if (btn.tag == 102) {
        NSLog(@"银行卡所在城市");
       
        XDGetCityViewController *getCity = [[XDGetCityViewController alloc] init];
        
        [self.navigationController pushViewController:getCity animated:YES];
        
        
    } else if (btn.tag == 103){
        NSLog(@"银行卡所在支行");
        if (self.bankNum.text.length > 14 && self.bankNameBtn.titleLabel.text && self.cityLb.text.length > 0) {
            XDGetSubBankNameController *getSubBankName = [[XDGetSubBankNameController alloc] init];
            
            getSubBankName.cityCode = self.cityCode;
            getSubBankName.bankCode = self.bankCode;
            getSubBankName.bankAccountNo = [self.bankNum.text stringByReplacingOccurrencesOfString:@" " withString:@""];
            [self.navigationController pushViewController:getSubBankName animated:YES];
        } else {
            
            if (!self.bankNum.text.length) {
                [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入银行卡号" view:self.view];
            } else if (self.bankNum.text.length < 14 ||  self.bankNameBtn.titleLabel.text) {
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入正确的银行卡号" view:self.view];
            } else if (!self.cityLb.text.length) {
                [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请选择银行卡所在城市" view:self.view];
            }
        }
       
    }
    
}

- (void)nextBtnClick {
    
    // 提现下一步
    NSString *bankNumber = [[self.bankNum.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSString *bankName = [[self.bankNameBtn.titleLabel.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    self.bankCode = self.bankCode ? self.bankCode : @"";
    if (!self.bankNum.text) {
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入银行卡号" view:self.view];
    } else if ([self.cityLb.text isEqualToString:@"请选择银行卡所在城市"] || self.cityLb.text == nil) {
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请选择银行卡所在城市" view:self.view];
    } else if ([self.subBranch.text isEqualToString:@"请选择银行卡所在支行"] || self.subBranch.text == nil) {
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请选择银行卡所在支行" view:self.view];
        
    } else {
        
        NSDictionary * param = @{@"method":@"bindBankCard",@"bankNumber":bankNumber,@"bankCode":self.bankCode,@"bindType":@"2",@"bankName":bankName,@"accountProvince":self.accountProvince,@"accountCity":self.cityLb.text,@"brachName":self.subBranch.text};
        [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {

            if ([responseObject[@"code"] isEqualToString:@"100000"]) {
                
                XDCheckWithdrawViewController *checkWithdraw = [[XDCheckWithdrawViewController alloc] init];
                checkWithdraw.available = [responseObject[@"result"][@"available"] stringValue];
                [self.navigationController pushViewController:checkWithdraw animated:YES];
                
                
            } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
                
                
            } else {
                
                [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
        
    }

}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    

    if (textField.tag == 100) {
        
        
        NSString *bankNumber = [[textField.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *textFieldText = [bankNumber stringByAppendingString:string];
        if (textFieldText.length > 5 || string.length > 2) {
            NSDictionary * param = @{@"method":@"findInfoByBanlBin",@"bankNumber":textFieldText};
            [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
                
                
                
                if ([responseObject[@"code"] isEqualToString:@"100000"]) {
                    
                    
                    NSDictionary *dic = responseObject[@"result"][@"bankValidate"];
                    [[SDWebImageManager sharedManager] downloadImageWithURL:dic[@"bankIconUrl"] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                        
                        
                        [self.bankNameBtn setImage:[self OriginImage:image scaleToSize:CGSizeMake(20.0, 20.0)] forState:UIControlStateNormal];
                        [self.bankNameBtn setTitle:dic[@"bankName"] forState:UIControlStateNormal];
                        [self.bankNameBtn setTitleColor:kColorRGB(51, 51, 51) forState:UIControlStateNormal];
                        
                        self.bankCode = dic[@"bankCode"];
                        
                        if (textFieldText.length > 14 && self.bankCode && self.cityLb.text.length > 0 && self.subBranch.text.length > 0) {
                            self.nextBtn.enabled = YES;
                        } else {
                            self.nextBtn.enabled = NO;
                        }
                        
                    }];
                    
                } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
                    
                    
                } else {
                    
//              [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
                }
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
                
            }];
            
        }
       
        // 4位分隔银行卡卡号
        NSString *text = [textField text];
        
        NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789\b"];
        string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) {
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入正确的银行卡号" view:self.view];
            return NO;
        }
        
        text = [text stringByReplacingCharactersInRange:range withString:string];
        text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        NSString *newString = @"";
        while (text.length > 0) {
            NSString *subString = [text substringToIndex:MIN(text.length, 4)];
            newString = [newString stringByAppendingString:subString];
            if (subString.length == 4) {
                newString = [newString stringByAppendingString:@" "];
            }
            text = [text substringFromIndex:MIN(text.length, 4)];
        }
        
        newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]];
        
        if ([newString stringByReplacingOccurrencesOfString:@" " withString:@""].length >= 21) {
            return NO;
        }
        
        [textField setText:newString];
        
        return NO;
    }
    return YES;
}

-(UIImage*)OriginImage:(UIImage *)image scaleToSize:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    //Determine whether the screen is retina
    if([[UIScreen mainScreen] scale] == 2.0){
        
        UIGraphicsBeginImageContextWithOptions(size, NO, 2.0);
    }else{
        UIGraphicsBeginImageContext(size);
    }
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();        // 使当前的context出堆栈
    UIGraphicsEndImageContext();        // 返回新的改变大小后的图片
    return scaledImage;
}

- (void)hotCityNoti:(NSNotification *)noti {
    
    self.cityLb.text = noti.userInfo[@"city"];
    self.cityCode = noti.userInfo[@"cityCode"];
    self.accountProvince = noti.userInfo[@"province"];
    
}
- (void)subCityNoti:(NSNotification *)noti {
    
    self.subBranch.text = noti.userInfo[@"subBankName"];
    self.cityCode = noti.userInfo[@"cityCode"];
}

- (void)rightItem {
    
    NSLog(@"提现须知");
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:@"hotCityArr"];
//    subCityName
    [[NSNotificationCenter defaultCenter] removeObserver:@"subCityName"];
}
@end
